<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Equip extends Base
{
    protected $table = 'equip';
    protected $equipTypeTable = 'equip_type';
    protected $userEquipTable = 'user_equip';
    protected $equipStreamTable = 'equip_stream';
    protected $equipShelveTable = 'equip_shelve';

    //装备类型缓存
    protected $equipTypeKey = 'EQUIP:TYPELIST';//string EQUIP:TYPELIST => {string}
    //装备缓存
    protected $equipAllKey = 'EQUIP:ALL';//string EQUIP:ALL => {string}
    //用户正在使用的装备缓存
    protected $equipUserUseListKey = 'EQUIP:USERUSELIST:';//string EQUIP:USERUSELIST:{user_id} => {string}
    //货架装备缓存
    protected $equipShelveAllKey = 'EQUIP:SHELVEALL';//string EQUIP:SHELVEALL => {string}

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    //添加用户装备
    public function createUserEquip($userId, $equipId)
    {
        $info = $this->getUserEquipByUserIdEquipId($userId, $equipId);
        if(!empty($info)) {
            return $info['id'];
        }
        $data = [
            'user_id' => $userId,
            'equip_id' => $equipId,
        ];
        return DB::table($this->userEquipTable)->insertGetId($data);
    }

    /**
     * 更新用户装备数量
     * @param int $equip_type 类型 1=商店购买获得 2=抽奖获得 3=拍卖购买获得 4=拍卖退回获得 5=后台赠送 51=拍卖扣除
     * @param int $data_type 数据类型 1=钻石数量 2=抽奖记录ID 3=拍卖记录ID
     * @return bool
     */
    public function inc($user_id, $equip_id, $change_value, $equip_type, $data_id){
        if(empty($change_value)) {
            return true;
        }
        if(empty($user_id)) {
            return false;
        }
        if(empty($equip_id)) {
            return false;
        }
        $change_desc = '';
        $data_type = 0;
        //商店购买获得
        if($equip_type == 1) {
            $change_value = abs($change_value);
            $change_desc = '商店购买-获得';
            $data_type = 1;
        }
        //抽奖获得
        if($equip_type == 2) {
            $change_value = abs($change_value);
            $change_desc = '抽奖-获得';
            $data_type = 2;
        }
        //拍卖购买获得
        if($equip_type == 3) {
            $change_value = abs($change_value);
            $change_desc = '拍卖购买-获得';
            $data_type = 3;
        }
        //拍卖退回获得
        if($equip_type == 4) {
            $change_value = abs($change_value);
            $change_desc = '拍卖退回-获得';
            $data_type = 3;
        }
        //后台赠送
        if($equip_type == 5) {
            $change_value = abs($change_value);
            $change_desc = '系统赠送-获得';
            $data_type = 0;
        }
        //拍卖扣除
        if($equip_type == 51) {
            $change_value = 0 - abs($change_value);
            $change_desc = '拍卖-扣除';
            $data_type = 3;
        }

        $log = [];
        $log['user_id'] = $user_id;
        $log['equip_id'] = $equip_id;
        $log['change_value'] = $change_value;
        $log['change_desc'] = $change_desc;
        $log['equip_type'] = $equip_type;
        $log['data_id'] = $data_id;
        $log['data_type'] = $data_type;

        DB::table($this->userEquipTable)
            ->where('user_id', $user_id)
            ->where('equip_id', $equip_id)
            ->increment('num', $change_value);

        DB::table($this->equipStreamTable)->insert($log);

        return true;
    }

    //编辑装备
    public function updateEquip($equipId, $params)
    {
        $upData = [];
        if(!empty($params['equip_name'])) {
            $upData['equip_name'] = $params['equip_name'];
        }
        if(!empty($params['g_name'])) {
            $upData['g_name'] = $params['g_name'];
        }
        if(!empty($params['equip_level'])) {
            $upData['equip_level'] = $params['equip_level'];
        }
        if(!empty($params['can_sale'])) {
            $upData['can_sale'] = $params['can_sale'];
        }
        if(!empty($params['can_recoup'])) {
            $upData['can_recoup'] = $params['can_recoup'];
        }
        if(!empty($params['can_bag_show'])) {
            $upData['can_bag_show'] = $params['can_bag_show'];
        }
        if(!empty($params['small_image'])) {
            $upData['small_image'] = $params['small_image'];
        }
        if(!empty($params['image'])) {
            $upData['image'] = $params['image'];
        }
        if(!empty($params['jd_price'])) {
            $upData['jd_price'] = $params['jd_price'];
        }
        if(!empty($params['jd_sale_price_jd'])) {
            $upData['jd_sale_price_jd'] = $params['jd_sale_price_jd'];
        }
        if(!empty($params['jd_return_max'])) {
            $upData['jd_return_max'] = $params['jd_return_max'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->table)->where('equip_id', $equipId)->update($upData);

        $cacheKey = $this->equipAllKey;
        Redis::del($cacheKey);

        return $res;
    }

    //装备货架新增
    public function addEquipShelve($params)
    {
        $id = DB::table($this->equipShelveTable)->insertGetId($params);
        
        $cacheKey = $this->equipShelveAllKey;
        Redis::del($cacheKey);

        return $id;
    }

    //装备货架编辑
    public function editEquipShelve($shelveId, $params)
    {
        $upData = [];
        if(!empty($params['shelve_name'])) {
            $upData['shelve_name'] = $params['shelve_name'];
        }
        if(!empty($params['shelve_image'])) {
            $upData['shelve_image'] = $params['shelve_image'];
        }
        if(!empty($params['price_type'])) {
            $upData['price_type'] = $params['price_type'];
        }
        if(!empty($params['price'])) {
            $upData['price'] = $params['price'];
        }
        if(!empty($params['is_delete'])) {
            $upData['is_delete'] = $params['is_delete'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->equipShelveTable)->where('id', $shelveId)->update($upData);

        $cacheKey = $this->equipShelveAllKey;
        Redis::del($cacheKey);

        return $res;
    }

    //编辑装备类型
    public function editEquipType($id, $params)
    {
        $upData = [];
        if(isset($params['sort'])) {
            $upData['sort'] = $params['sort'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->equipTypeTable)->where('id', $id)->update($upData);

        $cacheKey = $this->equipTypeKey;
        Redis::del($cacheKey);

        return $res;
    }

    //更新用户脱掉所有装备
    public function updateUseUnuseAllEquip($userId)
    {
        DB::table($this->userEquipTable)
            ->where('user_id', $userId)
            ->where('if_use', 1)
            ->update(['if_use'=>0]);

        $cacheKey = $this->equipUserUseListKey.$userId;
        Redis::del($cacheKey);

        return 1;
    }

    //更新用户穿装备
    public function updateUseUseEquip($userId, $equipId)
    {
        DB::table($this->userEquipTable)
            ->where('user_id', $userId)
            ->where('equip_id', $equipId)
            ->where('if_use', 0)
            ->update(['if_use'=>1]);

        $cacheKey = $this->equipUserUseListKey.$userId;
        Redis::del($cacheKey);

        return 1;
    }

    /**
     * 获取装备类型
     */
    public function getEquipType(){
        $key = $this->equipTypeKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->equipTypeTable)
                ->orderBy('sort', 'desc')
                ->get()->toArray();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }

    /**
     * 根据ID获取单条数据
     */
    public function getEquipById($equipId){
        if(empty($equipId)) {
            return [];
        }

        $info = DB::table($this->table)
            ->where('equip_id', $equipId)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    /**
     * 根据IDs获取列表
     */
    public function getEquipByIds($equipIds=[]){
        if(empty($equipIds)) {
            return [];
        }

        $list = DB::table($this->table)
            ->whereIn('equip_id', $equipIds)
            ->get()->toArray();
        $list = self::objToArray($list);

        return $list;
    }

    /**
     * 获取所有装备数据
     */
    public function getEquipAll(){
        $cacheKey = $this->equipAllKey;
        $list = Redis::get($cacheKey);
        if(empty($list)){
            $list = DB::table($this->table)
                ->get()->toArray();
            $list = self::objToArray($list);
            if(!empty($list)) {
                foreach($list as $key=>$val) {
                    if($val['equip_type'] == 8) {
                        $val['childs'] = [];
                        foreach($list as $v2) {
                            if($val['equip_id'] == $v2['equip_pid']) {
                                $val['childs'][] = ['equip_id'=>$v2['equip_id'], 'equip_type'=>$v2['equip_type']];
                            }
                        }
                        $list[$key] = $val;
                    }
                }
                Redis::setex($cacheKey, 30*86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }
        $list = array_column($list, null, 'equip_id');

        return $list;
    }

    /**
     * 根据装备ID获取用户装备
     */
    public function getUserEquipByUserIdEquipId($userId, $equipId){
        if(empty($equipId) || empty($userId)) {
            return [];
        }

        $info = DB::table($this->userEquipTable)
            ->where('user_id', $userId)
            ->where('equip_id', $equipId)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    /**
     * 获取用户正在使用的装备
     */
    public function getUserEquipByUserId($userId){
        if(empty($userId)) {
            return [];
        }
        $key = $this->equipUserUseListKey.$userId;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->userEquipTable)
                ->where('user_id', $userId)
                ->where('if_use', 1)
                ->where('num', '>', 0)
                ->select(['id', 'user_id', 'equip_id', 'num', 'if_use'])
                ->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 3600, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        $res = [];
        if(!empty($list)) {
            $equipList = $this->getEquipAll();
            foreach($list as $val) {
                if(!empty($equipList[$val['equip_id']])) {
                    $item = $equipList[$val['equip_id']];
                    $item['small_image'] = build_image($item['small_image']);
                    $item['image'] = build_image($item['image']);
                    $res[] = $item;
                }
            }
        }

        return $res;
    }

    /**
     * 获取用户拥有的装备列表
     */
    public function getUserHasEquipList($page=1, $limit=20, $userId, $equipType){
        if(empty($userId)) {
            return [];
        }

        $query = DB::table($this->userEquipTable.' as a')
            ->join($this->table . ' as b', 'a.equip_id', '=', 'b.equip_id')
            ->select(['a.num', 'a.if_use', 'b.equip_id', 'b.equip_pid', 'b.equip_name', 'b.g_name', 'b.equip_type', 'b.equip_sex', 'b.equip_level', 'b.can_sale', 'b.can_recoup', 'b.small_image', 'b.image', 'b.u3d_spine', 'b.jd_price', 'b.jd_sale_price_jd'])
            ->where('b.can_bag_show', 1)
            ->where('a.num', '>', 0)
            ->where('a.user_id', $userId);
        if(!empty($equipType)) {
            $query = $query->where('b.equip_type', $equipType);
        }
        $query = $query->offset($page*$limit)->limit($limit)->orderBy('b.equip_level', 'desc');
        $list = $query->get();
        $list = self::objToArray($list);

        $res = [];
        if(!empty($list)) {
            $equipList = $this->getEquipAll();
            foreach($list as $val) {
                $val['small_image'] = build_image($val['small_image']);
                $val['image'] = build_image($val['image']);
                if($val['equip_type'] == 8) {
                    $val['childs'] = empty($equipList[$val['equip_id']]['childs']) ? [] : $equipList[$val['equip_id']]['childs'];
                }
                $res[] = $val;
            }
        }

        return $res;
    }

    /**
     * 获取货架装备
     */
    public function getEquipShelveList($equipType=0){
        $key = $this->equipShelveAllKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->equipShelveTable)
                ->where('is_delete', 0)
                ->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        $res = [];
        if(!empty($list)) {
            $equipList = $this->getEquipAll();
            foreach($list as $val) {
                if(!empty($equipList[$val['equip_id']])) {
                    if(!empty($equipType) && $equipType!=$equipList[$val['equip_id']]['equip_type']) {
                        continue;
                    }

                    $item = $equipList[$val['equip_id']];
                    unset($item['created_at'], $item['updated_at']);
                    $item['small_image'] = build_image($item['small_image']);
                    $item['image'] = build_image($item['image']);
                    $item['shelve_id'] = $val['id'];
                    $item['shelve_name'] = $val['shelve_name'];
                    $item['shelve_image'] = build_image($val['shelve_image']);
                    $item['price_type'] = $val['price_type'];
                    $item['price'] = $val['price'];
                    $res[] = $item;
                }
            }
        }
        array_multisort(array_column($res, 'equip_level'), SORT_DESC, $res);

        return $res;
    }

    /**
     * 根据装备ID获取货架装备
     */
    public function getEquipShelveByEquipId($equipId){
        $list = $this->getEquipShelveList();
        $list = array_column($list, null, 'equip_id');
        $info = empty($list[$equipId]) ? [] : $list[$equipId];

        return $info;
    }



}
